package com.shxzz.easy12306.services.ticket.service.handler.filter.purchase;

import com.shxzz.easy12306.framework.starter.convention.exceptions.ClientException;
import com.shxzz.easy12306.services.ticket.dao.entity.TrainDO;
import com.shxzz.easy12306.services.ticket.dao.mapper.TrainStationMapper;
import com.shxzz.easy12306.services.ticket.dto.req.PurchaseTicketReqDTO;
import com.shxzz.easy12306.services.ticket.dto.resp.TrainStationQueryRespDTO;
import com.shxzz.easy12306.services.ticket.service.TrainService;
import com.shxzz.easy12306.services.ticket.service.TrainStationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 车票购买参数合法性验证
 *
 * @author shxzz
 * @create 2024-03-06-14:10
 */
@RequiredArgsConstructor
@Component
public class TicketPurchaseParamVerifyChainFilter implements TicketPurchaseChainFilter {

    private final TrainStationService trainStationService;
    private final TrainService trainService;
    private final TrainStationMapper trainStationMapper;

    @Override
    public void handler(PurchaseTicketReqDTO requestParam) {
        TrainDO trainDO = trainService.getTrainInfo(requestParam.getTrainId());
        if (trainDO == null) {
            throw new ClientException("车次不存在");
        }
        List<TrainStationQueryRespDTO> trainStationQueryRespDTOS = trainStationService.listTrainStationQuery(requestParam.getTrainId());
        List<String> trainStopoverStationList = trainStationQueryRespDTOS.stream().map(TrainStationQueryRespDTO::getDeparture).toList();
        boolean isValid = validate(trainStopoverStationList, requestParam.getDeparture(), requestParam.getArrival());
        if(!isValid) {
            throw new ClientException("车站信息错误");
        }
    }

    private boolean validate(List<String> trainStopoverStationList, String departure, String arrival) {
        int departureIndex = trainStopoverStationList.indexOf(departure);
        int arrivalIndex = trainStopoverStationList.indexOf(arrival);
        return arrivalIndex >= 0 && departureIndex >= 0 && arrivalIndex > departureIndex;
    }

    @Override
    public int getOrder() {
        return 100;
    }
}
